///////////////////////////////////////////////////////////////////////////////
//提供落地方式扩展
//以下是扩展样例

#include "../logs/log.h"
#include <fstream>
#include <iostream>
#include <sstream>

enum class TimeGap
{

    GAP_SEC,
    GAP_MIN,
    GAP_HOUR,
    GAP_DAY,
};

class RollByTime : public Log::LogSink
{
private:
    std::string _basename; // 文件前缀名字
    std::ofstream _ofs;
    size_t _time_gap;  // 时间间隔
    size_t _open_time; // 打开文件时间
private:
    std::string creatNewFile()
    {
        time_t t = Log::util::date::getTime();
        struct tm lt;
        localtime_r(&t, &lt);
        std::stringstream filename;
        filename << _basename;
        filename << lt.tm_year + 1900; // 时间戳从1900年开始要加1900
        filename << lt.tm_mon + 1;     // 月份从0开始要加1
        filename << lt.tm_mday;
        filename << lt.tm_hour;
        filename << lt.tm_min;
        filename << lt.tm_sec;
        filename << ".log";
        return filename.str();
    }

public:
    // 构造需要传文件前缀名,文件允许最大值
    RollByTime(const std::string &basename, TimeGap gap_tpye) : _basename(basename)
    {
        switch (gap_tpye)
        {
        case TimeGap::GAP_SEC:
            _time_gap = 1;
            break;
        case TimeGap::GAP_MIN:
            _time_gap = 60;
            break;
        case TimeGap::GAP_HOUR:
            _time_gap = 3600;
            break;
        case TimeGap::GAP_DAY:
            _time_gap = 3600 * 24;
            break;
        }
        std::string pathname = creatNewFile();
        // 防止文件路径不存在,先创建文件路径
        Log::util::file::creatDirectory(Log::util::file::path(pathname));
        // 文件不存在打开时会自动创建,并以追加方式打开
        _ofs.open(pathname, std::ios::binary | std::ios::app);
        // 获取打开时间
        _open_time = Log::util::date::getTime() / _time_gap;
        // 判断是否打开成功
        assert(_ofs.is_open());
    }
    void log(const char *date, size_t len)
    {
        if (Log::util::date::getTime() / _time_gap != _open_time)
        {
            std::string pathname = creatNewFile();
            _ofs.close(); // 先关闭之前的
            _ofs.open(pathname, std::ios::binary | std::ios_base::app);
            // 判断是否打开成功
            assert(_ofs.is_open());
            _open_time = Log::util::date::getTime() % _time_gap;
        }
        assert(_ofs.good()); // 判断是否处于就绪状态
        _ofs.write(date, len);
    }
};

void log_test()
{

  Log::Logger::ptr rollbytime=Log::getLogger("rollByTime");
  for (size_t i = 0; i < 999999; i++)
  {
    rollbytime->debug("测试信息%d",i);
    rollbytime->info("测试信息%d",i);
    rollbytime->warn("测试信息%d",i);
    rollbytime->error("测试信息%d",i);
    rollbytime->fatal("测试信息%d",i);
  }
  

}

int main()
{
    Log::GlobalBuilder globa(Log::LoggerTpye::LOGGER_ASYNC);
    globa.buildLoggerName("rollByTime");
    globa.buildFormat("[%t][%p][%f:%l][%m][%c]%n");
    globa.buildSink<RollByTime>("./logfile/rollByTime-",TimeGap::GAP_SEC);
    globa.build();
    log_test();
    return 0;
}